package org.springframework.aop.org.springframework.aop.framework;

import org.springframework.aop.org.springframework.aop.AdvisedSupport;
import org.springframework.beans.util.ClassUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkDynamicAopProxy implements AopProxy {

    private AdvisedSupport advised;

    public JdkDynamicAopProxy(AdvisedSupport advised) {
        this.advised = advised;
    }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(ClassUtil.getDefaultClassLoader(), advised.getTargetSource().getTargetClass(),
                (proxy, method, args) -> {
                if (advised.getMethodMatcher().matches(method, advised.getTargetSource().getTarget().getClass())) {
                    return advised.getInterceptor().invoke(new ReflectMethodInvocation(method, args, advised.getTargetSource().getTarget()));
                } else {
                    return method.invoke(advised.getTargetSource().getTarget(), args);
                }
        });
    }
}
